// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use lazy_static::lazy_static;
use qwen72b::MemoryData;
use qwen72b::TyClient;

#[tokio::main]
async fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![init_process])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

// use tauri::{Manager, Window};
#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct Payload {
    message: String,
}

lazy_static! {
    // 使用 Mutex 包装可变变量，确保在多线程或异步环境中安全访问
    static ref CLIENT: TyClient = TyClient::new("sk-bf05ae0f78f1489c8a5994baa33a5b11".to_string());
}

#[tauri::command]
async fn init_process(main_window: tauri::Window, usermsg: String, memory: String) {
    let memory: Vec<MemoryData> = serde_json::from_str(&memory).unwrap();

    tokio::task::spawn(async move {
        let response = CLIENT.handle_sse(&usermsg, memory).await.unwrap();
        // 检查响应状态码
        if response.status().is_success() {
            // 处理 SSE 数据流
            let mut body = response.bytes_stream();
            use futures_util::StreamExt;
            let mut buffer = Vec::new();
            while let Some(chunk) = body.next().await {
                let chunk = chunk.unwrap();
                buffer.extend_from_slice(&chunk);
                // Process each SSE event
                while let Some(line) = buffer.iter().position(|&x| x == b'\n') {
                    let event = std::str::from_utf8(&buffer[..line]);
                    if let Ok(event) = event {
                        // tx.send().await.unwrap();
                        main_window.emit("botMsg", event.to_string()).unwrap();
                    }
                    buffer.drain(..line + 1);
                }
            }
        } else {
            println!("Request failed with status code: {}", response.status());
        }
    });
}
